const router = require('koa-router')();
let User = require('../models/user.js');
const { sign } = require('../libs/security');
router.prefix('/users');

/**
 * 获取用户的信息
 */
router.get('/getUserInfo', async (ctx, next) => {
  try {
    let user = await User.findOne({userId: ctx.userId}).select('-_id -roles -status -type -_id -password -createdAt -updatedAt');
    ctx.success(user);
  } catch (err) {
    throw err;
  }
});

/**
 * 修改用户信息
 */
router.post('/updateUserInfo', async (ctx, next) => {
  try {
    let { name, age, phone, email, avatar } = ctx.request.body;
    await User.update({userId: ctx.userId}, {$set: {
      name, age, phone, email, avatar
    }});
    ctx.success({msg: 'update successful'});
  } catch (err) {
    throw err;
  }
});

/**
 * 获取用户的列表
 */
router.get('/getUserLists', async (ctx, next) => {
  try {
    let { phone = '', email = '', page = 1, size = 10 } = ctx.query;
    let obj = {};
    if (phone) {
      obj.phone = phone;
    }
    if (email) {
      obj.email = email;
    }
    let uLists = await User.find(obj).skip((+page - 1) * size).limit(+size);
    let total = await User.find(obj).count();
    ctx.success({uLists, total});
  } catch (err) {
    throw err;
  }
});

/**
 * 编辑用户
 */
router.post('/updateUser', async (ctx, next) => {
  try {
    let { usid, status = false, type = '02', name, email, phone, gender = 1, avatar = '', password = '' } = ctx.request.body;
    let obj = {};
    status && (obj.status = status);
    name && (obj.name = name);
    email && (obj.email = email);
    phone && (obj.phone = phone);
    obj.gender = gender;
    avatar && (obj.avatar = avatar);
    password && (obj.password = sign(password));
    if (!usid) {
      usid = ctx.userId;
    }
    type && (obj.type = type);
    obj.operator = ctx.userId;
    await User.updateOne({ userId: usid }, {$set: obj});
    ctx.success({msg: 'modify success'});
  } catch (err) {
    throw err;
  }
});
/**
 * 添加用户
 */
router.post('/addUser', async (ctx, next) => {
  try {
    let { status = true, type = '02', name, email, phone, password = '' } = ctx.request.body;
    let u = await User.findOne({$or: [{phone}, {email}]});
    if (u) {
      if (u.email) {
        throw new Error('邮箱以存在');
      }
      if (u.phone) {
        throw new Error('手机号已存在');
      }
      throw new Error('用户已存在');
    } else {
      await User.create({
        status, type, name, email, phone, password
      });
      ctx.success({msg: `创建用户成功`});
    }
  } catch (err) {
    throw err;
  }
});

/**
 *重置密码
 */
router.post('/resetPwd', async (ctx, next) => {
  try {
    let { usid, password } = ctx.request.body;
    let pwd = sign(password);
    await User.update({ userId: usid }, {$set: {password: pwd}});
    ctx.success({msg: `resetpwd sucessful`});
  } catch (err) {
    throw err;
  }
});

module.exports = router;
